﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Permissions;

using System.Collections;
using Microsoft.SharePoint;
using Microsoft.SharePoint.UserCode;
using Microsoft.SharePoint.Workflow;

namespace EFSBWFActivities
{
    [ToolboxItemAttribute(true)]
    public class getMultiLookupFromStringSB
    {
        //convert 'value1;value3;value99;' to 'value1;#1;#value3;#4;#value99;#6'
        #region Logging
        //[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public static void LogDebugInfo(SPUserCodeWorkflowContext context, string strMessage)
        {
#if DEBUG
            Log(context, strMessage);
#endif
        }

        //[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public static void Log(SPUserCodeWorkflowContext context, string strMessage)
        {
            using (SPSite site = new SPSite(context.CurrentWebUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPWorkflow.CreateHistoryEvent(web, context.WorkflowInstanceId, 0,
                        web.CurrentUser, TimeSpan.Zero, "getMultiLookupFromStringSB", strMessage, string.Empty);
                }
            }
        }

        #endregion

        //[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public static Hashtable Execute(SPUserCodeWorkflowContext context, string ReferenceList, string ReferenceColumn, string LookupString)
        {
            Hashtable results = new Hashtable();
            results["Except"] = string.Empty;

            //LogDebugInfo(context, string.Format("getMultiLookupFromStringSB.Execute() begin... strFieldName={0}", strFieldName));
            SPList objSPList = null;
            string strMultiLookupValue = string.Empty;
            string strTmp = string.Empty;

            try
            {
                using (SPSite objSPSite = new SPSite(context.CurrentWebUrl))
                {
                    using (SPWeb objSPWeb = objSPSite.OpenWeb())
                    {
                        LogDebugInfo(context, @"Site.ServerRelativeUrl=" + objSPSite.ServerRelativeUrl);
                        LogDebugInfo(context, @"Web.ServerRelativeUrl=" + objSPWeb.ServerRelativeUrl);
                        LogDebugInfo(context, @"ReferenceList=" + ReferenceList);

                        objSPList = objSPWeb.Lists[new Guid(ReferenceList)];
                        if (objSPList == null)
                        {
                            strTmp = @"list title(" + ReferenceList + ") is invalid";
                            Log(context, strTmp);
                            results["Except"] = strTmp;
                            return results;
                        }

                        if (string.IsNullOrEmpty(LookupString) == false)
                        {
                            string[] oLookupArray = LookupString.Split(';');
                            Dictionary<string, int> oDict = new Dictionary<string, int>();

                            SPListItemCollection objItems = objSPList.Items;
                            foreach (SPListItem item in objItems)
                            {
                                oDict.Add(Convert.ToString(item[ReferenceColumn]), item.ID);
                            }

                            foreach (string oLookup in oLookupArray)
                            {
                                if (string.IsNullOrEmpty(oLookup) == false)
                                {
                                    //strMultiLookupValue += string.Format(@"{0};#{1};#", oLookup, oDict[oLookup]);
                                    strMultiLookupValue += string.Format(@"{0};#{1};#", oDict[oLookup], oLookup);
                                }
                            }

                            if (strMultiLookupValue.Length > 1)
                            {
                                strMultiLookupValue = strMultiLookupValue.Substring(0, strMultiLookupValue.Length - 2);
                            }
                        }
                        LogDebugInfo(context, @"strMultiLookupValue=" + strMultiLookupValue);

                        results["MultiLookupValue"] = strMultiLookupValue;

                        //LogDebugInfo(context, string.Format("getMultiLookupFromStringSB.Execute() completed."));
                    }
                }
            }
            catch (Exception ex)
            {
                Log(context, string.Format(@"ex.Message = {0}", ex.Message));
                Log(context, string.Format(@"ex.StackTrace = {0}", ex.StackTrace));
                //results["Result"] = "Failure";
                //results["Except"] = ex.ToString();
            }

            results["Status"] = "Success";
            return results;
        }
    }
}
